#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author  : 邢建辉
# @Email   : xjh_0125@sina.com
# @Time    : 2021/12/30 9:44
# @Software: PyCharm
# @File    : l1814_count_nice_pairs.py

import math


class Solution(object):
    def countNicePairs(self, nums):
        '''
        找规律
        num1 + rev(num2) == num2 + rev(num1)
        num1 -rev(num1) = num2 - rev(num2)
        :param nums:
        :return:
        '''
        dic = {}
        mod = 10 ** 9 + 7
        for num in nums:
            sub = num - int(str(num)[::-1])
            dic[sub] = dic.get(sub, 0) + 1
        res = 0
        for item in dic.values():
            res += item * (item - 1) / 2
        return res % mod

    def countNicePairs_2(self, nums):
        '''
        暴力解法，超时
        :param nums:
        :return:
        '''
        nums = sorted(nums)
        new_nums = []
        dic = {}
        mod = 10 ** 9 + 7
        for num in nums:
            if num in dic:
                dic[num][0] += 1
            else:
                dic[num] = [1, Solution.rev(num)]
                new_nums.append(num)
        res = 0
        print(dic)
        for v in dic.values():
            if v[0] > 1:
                res += Solution.sum_fib(v[0] - 1)
        for i in range(len(new_nums)):
            for j in range(i + 1, len(new_nums)):
                num1, num2 = new_nums[i], new_nums[j]
                if Solution.check_nice(num1, num2, dic):
                    res += dic[num1][0] * dic[num2][0]
        return res % mod

    @staticmethod
    def sum_fib(num):
        return (1 + num) * (num / 2)

    @staticmethod
    def check_nice(num1, num2, dic):
        return num1 + dic[num2][1] == num2 + dic[num1][1]

    @staticmethod
    def rev(num):
        return int(str(num)[::-1])


if __name__ == '__main__':
    s = Solution()
    nums = [11, 1, 1, 1, 1, 11, 11, 1, 1, 11]
    # nums = [13, 10, 35, 24, 76]
    print(s.countNicePairs(nums))
    print(Solution.rev(120))
